<?php

namespace Console\Supports;

use Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;

class KeyGenerate extends Command
{

    protected static $defaultName = 'key:generate';

    protected function configure()
    {
        $this->setDescription('生成系统加密密钥');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $envFile = ROOT_PATH . 'env.yaml';
        $envRs = Yaml::parseFile($envFile);

        if (!isset($envRs['APP']) || !isset($envRs['APP']['KEY'])) {
            throw new Exception('配置文件错误');
        }

        $envRs['APP']['KEY'] = 'base64:' . base64_encode(random_bytes(32));

        $envRs = Yaml::dump($envRs);

        file_put_contents($envFile, $envRs);

        $output->writeln('<info>系统密钥已生成</>');

        return 0;
    }
}
